package com.manager.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.manager.model.SysAdmin;
import com.manager.model.SysLink;

public class ManagerFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResp = (HttpServletResponse) response;

		String webUrl = httpReq.getRequestURI().replace('\\', '/');
		String contextPath = httpReq.getContextPath();
		String path = webUrl.substring(contextPath.length());
		// System.out.println(path);
		if (path.indexOf("/admin") == 0) {
			String login_path = "/admin/login.jsp";
			String login_action = "/admin/login.html";
			String exit_action = "/admin/exit.html";
			String admin_noRight = "/errors/admin_noRight.jsp";
			HttpSession session = httpReq.getSession();
			SysAdmin sysAdmin = (SysAdmin) session.getAttribute("sys_admin");
			if (sysAdmin == null) {
				if (!path.equals(login_path) && !path.equals(login_action)) {
					httpResp.sendRedirect(contextPath + login_path);
				} else
					chain.doFilter(request, response);
			} else {
				/*
				 * chain.doFilter(request, response);
				 */
				List<SysLink> links = sysAdmin.getLinks();
				if (inList(path, links) || path.equals(exit_action)) {
					chain.doFilter(request, response);
				} else {
					httpResp.sendRedirect(contextPath + admin_noRight);
				}
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	private boolean inList(String path, List<SysLink> links) {
		boolean state = false;
		if (links == null || path == null)
			return false;
		for (SysLink link : links) {
			String url = link.getLinkUrl();
			if (url == null || "".equals(url.trim()))
				continue;
			if (path.indexOf(url) == 0) {
				return true;
			}
		}
		return state;
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
